<template>
	<view>
		<an-nav-bar title="在线支付"> </an-nav-bar>
		<view class="box">
			<view class="order">
				<view style="text-align: center;">
					支付剩余时间<uni-countdown :show-day="false" :day="0" :hour="countdown[0]" :minute="countdown[1]" :second="countdown[2]" @timeup="countdownFinish"></uni-countdown>
				</view>
				<view class="money">
					￥<text>{{tradeDetail.price}}</text>
				</view>
			</view>
			<view class="pay">
				<view class="head">选择支付方式</view>
				<view class="main">
					<view class="item" v-if="support('ALIPAY')" @click="checkPayType('ALIPAY')">
						<view class="alipay"></view>
						<view class="name">支付宝支付</view>
						<view class="selected" :class="{'check':payType == 'ALIPAY'}"></view>
					</view>
					<view class="item" v-if="support('WECHAT')" @click="checkPayType('WECHAT')">
						<view class="wechat"></view>
						<view class="name">微信支付</view>
						<view class="selected" :class="{'check':payType == 'WECHAT'}"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="tips">
			<view class="t">提示：</view>
			<view class="">1、在线支付的订单是平台处理退款、赔偿的唯一凭证。</view>
			<view class="">2、一切不经平台的线下协议、付款均不在平台受理范围内，平台不负任何责任。</view>
		</view>
		<view class="btn">
			<button @click="pay">确认支付</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				client: 'APP', //APP,NATIVE,JSAPI,H5,MP
				clientType: 'APP', //APP,NATIVE,JSAPI,H5,MP
				orderType: "ORDER", //ORDER=订单,RECHARGE=充值魔豆,CUSTOMER_LEVEL_UP=升级vip
				sn: "",
				tradeDetail: {},
				payType: "",
				countdown: [
					0,35,0
				],
				timer: '',
			};
		},
		onLoad(option) {
			// #ifdef APP
			this.client = "APP"
			this.clientType = "APP"
			// #endif
			// #ifdef H5
			this.clientType = "H5"
			this.client = "H5"
			
			// 公众号支付
			if (/(MicroMessenger)/i.test(navigator.userAgent)) {
				this.clientType = "WECHAT_MP"
				this.client = "JSAPI"
			}
			// #endif
			if (option.orderType) {
				this.orderType = option.orderType
			}
			this.sn = option.id
			this.$http.get('/app/payment/cashier/tradeDetail', {
				clientType: this.clientType,
				orderType: this.orderType,
				sn: this.sn
			}).then(res => {
				this.tradeDetail = res.data
				if (this.tradeDetail.support.length >= 1) {
					this.payType = this.tradeDetail.support[0]
				}
				
				this.getCountdown()
			})
		},
		onShow() {
			this.checkOrderStatus()
		},
		methods: {
			pay() {
				let openid = uni.getStorageSync('openid')||'oVCQCxErxbBNSsRP3qsK1CbCoisE'
				this.$http.get(`/app/payment/cashier/pay/${this.payType}/${this.client}`, {
					clientType: this.clientType,
					orderType: this.orderType,
					sn: this.sn,
					openid: openid,
				}).then(res => {
					// #ifdef APP-PLUS
					uni.requestPayment({
						provider: 'wxpay',
						orderInfo: res.data,
						success: (e) => {
							// this.checkOrderStatus()
						},
						fail: (e) => {}
					})
					// #endif
					
					//  #ifdef H5
					if (/(MicroMessenger)/i.test(navigator.userAgent)) {
						console.log("======11")
						// 公众号支付
						let _res = JSON.parse(res.msg)
						if (typeof(WeixinJSBridge) == "undefined") {
							if (document.addEventListener) {
								document.addEventListener('WeixinJSBridgeReady', () => {
									this.doWeiXinMpPay(_res)
								}, false)
							} else if (document.attachEvent) {
								document.attachEvent('WeixinJSBridgeReady', () => {
									this.doWeiXinMpPay(_res)
								})
								document.attachEvent('onWeixinJSBridgeReady', () => {
									this.doWeiXinMpPay(_res)
								})
							}
						} else {
							this.doWeiXinMpPay(_res)
						}
					} 
					else if(this.payType == 'ALIPAY') {
						console.log("======22")
						//var htmlObject = document.createElement('div');
						var formHtml = res.msg.replace("display:none", "");
						//htmlObject.innerHTML = formHtml;
					
						document.querySelector('body').innerHTML = formHtml;
						//document.querySelector('body').append(htmlObject);
						document.forms[0].submit();
					}
					else {
						console.log("======33")
						console.log("_res.h5_url："+_res.h5_url)
						let _res = JSON.parse(res.msg)
						window.location.href=_res.h5_url
					}
					// #endif
				}).catch(e => {
					// console.log(e)
				})
			},
			checkOrderStatus(){
				if (!this.$common.checkPageRoute('pages/pay/pay')) {
					clearInterval(this.timer)
					return
				}
				
				this.$http.get('/appNoAuth/payment/cashierCallback/result', {
					clientType: this.clientType,
					orderType: this.orderType,
					sn: this.sn,
				}).then(res => {
					if (res && res.data){
						uni.showToast({
							icon: 'none',
							title: '支付成功！'
						})
						
						switch(this.orderType)
						{
						    case 'ORDER':
								uni.redirectTo({
									url: '/pages/my/order'
								});
						        break;
						    case 'RECHARGE':
								uni.redirectTo({
									url: '/pages/u/integral/index'
								});
						        break;
						    case 'CUSTOMER_LEVEL_UP':
								uni.switchTab({
									url: '/pages/tabbar/my'
								});
						        break;
						    default:
								uni.switchTab({
									url: '/pages/s/index/index'
								});
						}
					}
					
					clearInterval(this.timer)
					this.timer = setTimeout(() => {
						this.checkOrderStatus()
					}, 1000)
				})
			},
			support(type) {
				if (this.tradeDetail.support) {
					if (this.tradeDetail.support.indexOf(type) >= 0) {
						return true
					} else {
						return false
					}
				} else {
					return false
				}
			},
			checkPayType(type){
				this.payType = type;
			},
			getCountdown(){
				let second = (this.tradeDetail.autoCancel-new Date().getTime())/1000
				
				let h = parseInt(second / 60 / 60 % 24)
				let m = parseInt(second / 60 % 60)
				let s = parseInt(second % 60)

				this.countdown=[h,m,s]
			},
			countdownFinish(){
				uni.redirectTo({
					url: '/pages/my/order'
				})
			},
			doWeiXinMpPay(data) {
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": data.appId,
						"timeStamp": data.timeStamp,
						"nonceStr": data.nonceStr,
						"package": data.package,
						"signType": data.signType,
						"paySign": data.paySign
					},
					function(res) {
						// alert('code:' + res.err_code + '=desc:' + res.err_desc + '=msg:' + res.err_msg)
						/*
						get_brand_wcpay_request:ok	支付成功
						get_brand_wcpay_request:cancel	支付过程中用户取消
						get_brand_wcpay_request:fail	支付失败
						*/
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							uni.showToast({
								title: '支付成功',
								icon: 'none'
							})
							location.reload();
						}
					}
				)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.btn {
		width: 620rpx;
		height: 80rpx;

		margin: 100px auto 50px;

		button {
			width: 620rpx;
			cursor: pointer;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			text-align: center;
			color: #fff;
			border: none;
			font-size: 28rpx;
			background: linear-gradient(90deg, #d7b075, #aa8050);
			outline: none;
		}
	}

	.tips {
		font-size: 24rpx;
		color: #999;
		padding: 0 30rpx;

		>view {
			margin-bottom: 8rpx;
		}

		.t {
			font-size: 26rpx;
			margin-top: 10px;
		}
	}

	.box {
		width: 100%;
		padding: 0 30rpx;
		box-sizing: border-box;
		margin-top: 30rpx;
		overflow: hidden;

		.pay {
			float: left;
			width: 100%;
			background: #fff;
			border-top: 2rpx solid #eee;

			.head {
				float: left;
				width: 100%;
				padding-top: 46rpx;
				padding-left: 40rpx;
				box-sizing: border-box;
				color: #333;
				font-size: 28rpx;
			}

			.main {
				float: left;
				width: 100%;
				box-sizing: border-box;
				color: #333;
				font-size: 28rpx;
				padding-left: 40rpx;

				.item {
					float: left;
					width: 100%;
					height: 116rpx;
					padding: 30rpx 40rpx 30rpx 0;
					box-sizing: border-box;
					overflow: hidden;
					border-bottom: 2rpx solid #eee;

					&:first-child {
						margin-top: 0;
					}

					.name {
						float: left;
						height: 56rpx;
						line-height: 56rpx;
						margin-left: 24rpx;
					}

					.alipay {
						float: left;
						width: 56rpx;
						height: 56rpx;
						background: url(/static/pay_alipay.png) no-repeat 50%;
						background-size: 56rpx auto;
					}

					.wechat {
						float: left;
						width: 56rpx;
						height: 56rpx;
						background: url(/static/pay_wechat.png) no-repeat 50%;
						background-size: 56rpx auto;
					}

					.selected {
						float: right;
						width: 30rpx;
						height: 56rpx;
						background: url(/static/icon_check.png) no-repeat 0;
						background-size: 30rpx auto;
					}

					.check {
						background: url(/static/icon_checked.png) no-repeat 0;
						background-size: 30rpx auto;
					}
				}
			}
		}

		.order {
			float: left;
			width: 100%;
			height: 320rpx;
			background: #fff;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.uni-countdown {
				text-align: center;
			}

			.money {
				width: 100%;
				height: 120rpx;
				line-height: 120rpx;
				color: #aa8050;
				font-size: 36rpx;
				text-align: center;

				text {
					font-size: 48rpx;
				}
			}

			.detail {
				float: left;
				width: 100%;
				height: 100rpx;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				line-height: 100rpx;
				color: #666;
				font-size: 24rpx;

				&::after {
					display: block;
					content: "";
					width: 14rpx;
					height: 26rpx;
					background: url(/static/grey-arrow-right.png) no-repeat;
					background-size: 100% auto;
					margin-left: 10rpx;
					transform: translateY(1px);
				}
			}
		}
	}
</style>
